package com.itheima.web.controller;

import cn.hutool.captcha.LineCaptcha;
import com.itheima.domain.db.Admin;
import com.itheima.web.interceptor.AdminHolder;
import com.itheima.web.manager.AdminManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
public class AdminController {

    @Autowired
    private AdminManager adminManager;

    //生成验证码图片
    @GetMapping("/system/users/verification")
    public void verification(String uuid, HttpServletResponse response) throws IOException {
        //1. 调用manager生成验证码
        LineCaptcha lineCaptcha = adminManager.genCaptcha(uuid);

        //2. 使用响应流将验证码写回浏览器
        response.setContentType("image/jpeg");
        lineCaptcha.write(response.getOutputStream());
    }

    //管理员登录
    @PostMapping("/system/users/login")
    public Map<String, String> login(@RequestBody Map<String, String> paramMap) {

        //1. 获取请求参数
        String username = paramMap.get("username");
        String password = paramMap.get("password");
        String verificationCode = paramMap.get("verificationCode");
        String uuid = paramMap.get("uuid");

        //2. 调用manager登录
        String token = adminManager.login(username, password, verificationCode, uuid);

        //3. 返回token
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token", token);
        return tokenMap;
    }


    //获取管理员基本信息
    @PostMapping("/system/users/profile")
    public Map<String, String> AdminProfile(@RequestHeader("Authorization") String token) {
        //获取登录用户信息
         Admin admin = AdminHolder.getAdmin();

        //直接返回
        Map<String, String> map = new HashMap<>();
        map.put("uid", admin.getId() + "");
        map.put("username", admin.getUsername());
        map.put("avatar", admin.getAvatar());
        return map;
    }

    //管理员退出
    @PostMapping("/system/users/logout")
    public void logout(@RequestHeader("Authorization") String token) {
        //去掉token中的Bearer
        token = token.replaceAll("Bearer ", "");

        //调用manager删除token
        adminManager.logout(token);
    }


}
